<template>
    <!-- 上面搜索栏部分 -->
    <div class="search-box">
        <div class="flex">
            <div>
                <el-icon>
                    <Search />
                </el-icon>
                <span>筛选搜索</span>
            </div>
            <div>
                <el-button @click="submitFn" type="primary">查询搜索</el-button>
            </div>
        </div>
        <div style="padding-top: 20px">
            <!-- 在input里面回车会造成刷新，大家今晚可以尝试解决一下 -->
            <!-- 在有多个搜索框的情况下添加全部清空功能 -->
            <el-form @submit.prevent="submitFn" ref="searchFormRef" :model="listParams">
                <el-form-item label="输入搜索：" label-width="120px">
                    <!-- @keyup.enter 回车事件 -->
                    <!-- <el-input v-model="listParams.keyword" placeholder="请输入账号、姓名" @keyup.enter="submitFn" /> -->
                    <el-input v-model="listParams.keyword" placeholder="品牌名称/关键字" />
                </el-form-item>
            </el-form>
        </div>
    </div>
    <!-- 添加按钮 -->
    <div class="add-box">
        <div class="left">
            <el-icon>
                <Tickets />
            </el-icon>
            <span>数据列表</span>
        </div>
        <el-button @click="router.push(`/pms/addBrand`)">添加
        </el-button>
    </div>
    <!-- table表格部分 -->
    <el-table :data="tableData" border cell-class-name="center" style="width: 100%" @select="addFn1"
        @select-all="addFn2">
        <el-table-column type="selection" width="55" show-overflow-tooltip />
        <el-table-column class-name="center" prop="id" label="编号"> </el-table-column>
        <el-table-column class-name="center" prop="name" label="品牌名称"></el-table-column>
        <el-table-column class-name="center" prop="firstLetter" label="品牌首字母"></el-table-column>
        <el-table-column class-name="center" prop="sort" label="排序"></el-table-column>
        <el-table-column class-name="center" label="品牌制造商" width="95">
            <template #default="scope">
                <el-switch v-model="scope.row.factoryStatus" :active-value="1" :inactive-value="0"
                    @change="changeFactory(scope.row)">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column class-name="center" label="是否显示" width="85">
            <template #default="scope">
                <el-switch v-model="scope.row.showStatus" :active-value="1" :inactive-value="0"
                    @change="changeshowStatus(scope.row)">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column class-name="center" label="相关">
            商品:<el-button link type="primary">
                100
            </el-button>
            评价:<el-button link type="primary">
                1000
            </el-button>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column class-name="center" label="操作">
            <template #default="scope">
                <el-button @click="router.push(`/pms/addBrand?id=${scope.row.id}`)">
                    编辑
                </el-button>
                <el-button type="danger" @click="delFn(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!--  批量操作 -->
    <div class="left">
        <el-select v-model="changval" class="m-2" placeholder="批量操作" size="large" placement="top">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" @click="changsFn">确定</el-button>
    </div>
    <!-- 底部分页 -->
    <ElConfigProvider :locale="zhCn">
        <el-pagination v-model:currentPage="listParams.pageNum" v-model:page-size="listParams.pageSize" background
            layout="total, sizes, prev, pager, next ,jumper" :total="total" @size-change="pageSizeChagne"
            @current-change="currentChagne" :page-sizes="[5, 10, 15]" />
    </ElConfigProvider>
</template>
<script setup lang='ts'>import { user } from '@/api';
import { reactive, ref, toRefs } from 'vue';
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { Tickets } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

interface IState {
    tableData: IUserModel[];
    listParams: IUserListParams;
    total: number
}
// 一般如果遇上有部分数据是复杂类型，希望它们是响应式的，一般先准备一个总的state
const state = reactive<IState>({
    tableData: [],
    listParams: {
        keyword: "",
        pageNum: 1,
        pageSize: 10,
    },
    total: 0
})

const getbrandList = () => {
    user.getbrandlistApi(state.listParams).then((res) => {
        if (res.code === 200) {
            state.tableData = res.data.list;
            state.total = res.data.total;
        }
    })
}
getbrandList();

// 用来搜索框方法，进行重新渲染
const submitFn = () => {
    // 搜索一定要把页码回到第一页
    state.listParams.pageNum = 1
    // 重新请求一个数组回来把数据渲染到表格里面
    getbrandList();
};

const pageSizeChagne = (val: number) => {
    getbrandList();
};


const currentChagne = (val: number) => {
    getbrandList();
}

//更新品牌制造商状态
const changeFactory = (row: any) => {

    user
        .changefactoryStatusApi({
            ids: row.id,
            factoryStatus: row.factoryStatus,
        })
        .then((res) => {
            ElMessage({
                message: res.message,
                type: res.code === 200 ? "success" : "error",
            });


        }).catch((err) => {

            row.factoryStatus = row.factoryStatus === 1 ? 0 : 1;
        })

}

//更新更新显示状态
const changeshowStatus = (row: any) => {

    user.changeshowStatusApi({
        ids: row.id,
        showStatus: row.showStatus,
    })
        .then((res) => {
            ElMessage({
                message: res.message,
                type: res.code === 200 ? "success" : "error",
            });


        }).catch((err) => {

            row.showStatus = row.showStatus === 1 ? 0 : 1;
        })

}

// 记录勾选的id
const changeArr = ref<number[]>([])
const addFn1 = (rows: any) => {
    let arr: number[] = []
    arr.push(rows.map((item: any) => { return item.id }))

    changeArr.value = arr
}
const addFn2 = (selection: any) => {
    let arr: number[] = []
    arr.push(selection.map((item: any) => { return item.id }))
    changeArr.value = arr

}

//  批量操作
const changval = ref('')
const options = [
    {
        value: 1,
        label: '显示品牌',
    },
    {
        value: 2,
        label: '隐藏品牌',
    },
]
const changsFn = () => {
    if (changval.value) {
        if (changeArr.value.length !== 0) {
            let str = changeArr.value.join(",")
            if(changval.value == '1'){
                changesShowStatus(str,1)    
            }else{
                changesShowStatus(str,0)
            }
        }
        else{
            ElMessage.warning("请选择一条记录")
        }

    } else {
        ElMessage.warning("请选择批量操作类型")
    }
}
const changesShowStatus = (ids: string, showStatus: number) => {

    user.changeshowStatusApi({
        ids,
        showStatus,
    }).then((res) => { 
        ElMessage({
                message: res.message,
                type: res.code === 200 ? "success" : "error",
            });
        getbrandList();
    })
}

const delFn = (id:number) => {
    ElMessageBox.confirm("是否要删除该品牌", "提示", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
    }).then(() => {
        user.delbrandlistapi (id).then((res) => {
            if (res.code === 200) {
                ElMessage.success("删除成功！")
                getbrandList();
            }
        })
    })
}

let { tableData, listParams, total } = toRefs(state)
</script>
<style lang="less" scoped>
.search-box {
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0px 0px 6px 0px gray;
    margin-bottom: 30px;

    .flex {
        display: flex;
        justify-content: space-between;
    }

    .el-icon {
        margin-right: 10px;
    }

    .el-input {
        width: 250px;
    }
}

.add-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    margin-bottom: 20px;
    border-radius: 5px;
    box-shadow: 0 0 4px 2px #ccc;

    .left {
        display: flex;
        align-items: center;
        padding: 0 10px;

        .el-icon {
            margin-right: 10px;
        }

    }
}

:deep(.center) {
    text-align: center;
}

.left{
    margin-top: 20px;
    float: left;
    .el-button{
        margin-left: 5px;
    }
}

.el-pagination {
    margin-top: 20px;
    float: right;
}
</style>